//
//  SettingIconViewController.m
//  ZYZB
//
//  Created by ENERGY on 2018/7/9.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "SettingIconViewController.h"
#import "AFNetworking.h"
#import "AFAppDotNetAPIClient.h"

@interface SettingIconViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (nonatomic,copy) void(^selectPhotoHandle)(UIImage *img);
@property (nonatomic, strong)UIImageView * iconImg;
@end

@implementation SettingIconViewController(networking)
//上传头像
- (void)upLoadPhoto{
    [self showprogressHUD];
    NSString * timeStr = [self currentTimeStr];
    //str
    NSDictionary * dic = @{
                           @"userName":[UserModel sharedInstanced].mobile,
                           @"phone":[UserModel sharedInstanced].mobile,
                           @"token":[UserModel sharedInstanced].token,
                           @"t":timeStr
                           };
    //sign
    NSDictionary * signDic = @{
                               @"userName":[UserModel sharedInstanced].mobile,
                               @"phone":[UserModel sharedInstanced].mobile,
                               @"token":[UserModel sharedInstanced].token,
                               @"t":timeStr,
                               @"merchantNo":@"80d709a97af1b8ab"
                               };
    SortMD5Code * md5Code = [[SortMD5Code alloc] init];
    //jsonDic和sign合为一个dic（为上传头像准备的方法）
    NSDictionary * uploadData = [md5Code getUploadImgWithStrDic:dic withSignDic:signDic];
////    http://120.78.157.132:82/   http://120.78.157.132:82/index.php/userInfo/index?api=api1003
    [[AFAppDotNetAPIClient sharedClient] POST:@"http://120.78.157.132:82/index.php/userInfo/index?api=api1003" parameters:uploadData constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *data = UIImageJPEGRepresentation(self.iconImg.image, .1);
        NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
        [formData appendPartWithFileData:data name:@"img" fileName:[NSString stringWithFormat:@"%ld.jpg",(NSUInteger)time] mimeType:@"image/jpeg"];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString * compareMD5Str = [md5Code encodeStringWithDictionary:responseObject];
        NSString * signResult = [responseObject objectForKey:@"sign"];//接到的json串sign字段
        NSDictionary * jsonData = [md5Code getNSDictionaryData:responseObject];//解析为字典数据
        if ([compareMD5Str isEqualToString:signResult]) {
            NSLog(@"成功");
            ShowMessage(jsonData[@"msg"]);
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            NSLog(@"失败");
            ShowMessage(jsonData[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
    }];
}
@end
@implementation SettingIconViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"设置头像";
    //返回按钮
    UIButton * backBtn = [[UIButton alloc] initWithFrame:CGRectMake(18/WIDTH_6_SCALE, 14/WIDTH_6_SCALE + 24 + 20, 24/WIDTH_6_SCALE, 30/WIDTH_6_SCALE)];
    [backBtn addTarget:self action:@selector(backBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setImage:[UIImage imageNamed:@"out"] forState:UIControlStateNormal];
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setUpFrame];//搭建控件
    
}
- (void)setUpFrame{
    self.iconImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 375/WIDTH_6_SCALE)];
    self.iconImg.backgroundColor = getColor(grayBGColor);
    [self.view addSubview:self.iconImg];
    //相册选择
    int btnBorderW = 58/WIDTH_6_SCALE;
    UIButton * albumBtn = [[UIButton alloc] initWithFrame:CGRectMake(btnBorderW, self.iconImg.bottom + 44/WIDTH_6_SCALE, SCREEN_WIDTH - btnBorderW * 2, 38/WIDTH_6_SCALE)];
    [self button:albumBtn withBGColor:[UIColor whiteColor] withLayerBorderColor:getColor(grayColor) withLayerBorderWith:1 withCornerRadius:6 withMasksToBounds:YES withViwe:self.view];
    [albumBtn setTitle:@"从相册选择" forState:UIControlStateNormal];
    albumBtn.titleLabel.font = DEF_FontSize_12;
    [albumBtn addTarget:self action:@selector(albumBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [albumBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    //拍照
    UIButton * cameraBtn = [[UIButton alloc] initWithFrame:CGRectMake(albumBtn.left, albumBtn.bottom + 26/WIDTH_6_SCALE, albumBtn.width, albumBtn.height)];
    [self button:cameraBtn withBGColor:[UIColor whiteColor] withLayerBorderColor:getColor(grayColor) withLayerBorderWith:1 withCornerRadius:6 withMasksToBounds:YES withViwe:self.view];
    [cameraBtn setTitle:@"拍一张照片" forState:UIControlStateNormal];
    cameraBtn.titleLabel.font = DEF_FontSize_12;
    [cameraBtn addTarget:self action:@selector(cameraBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [cameraBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
}
#pragma mark - action
- (void)backBtnClick:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)albumBtnClick:(UIButton *)sender{
    [self LocalPhoto];
}
- (void)cameraBtnClick:(UIButton *)sender{
    [self takePhoto];
}

//开始拍照
- (void)takePhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:nil];
    }else{
        NSLog(@"模拟其中无法打开照相机,请在真机中使用");
    }
}

//打开本地相册
- (void)LocalPhoto{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    [self presentViewController:picker animated:YES completion:nil];
}

//当选择一张图片后进入这里
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage* image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
//    if (self.selectPhotoHandle) {
//        self.selectPhotoHandle(image);
//    }
    self.iconImg.image = image;
    [self upLoadPhoto];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

@end
